package com.xinhua.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinhua.controller.util.R;
import com.xinhua.domain.Ssmp;
import com.xinhua.service.IbookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/ssmp")
public class SsmpContorller2 {

    @Autowired
    private IbookService ibookService;


    @GetMapping
    public R getAll() {
        return new R(true, ibookService.list());
    }

    //添加
    @PostMapping
    //通过请求体传json数据过来
    //RequestBody请求体参数  传递json格式的数据
    public R save(@RequestBody Ssmp ssmp) throws IOException {
        if (ssmp.getName().equals("123")) throw new IOException();
        boolean save = ibookService.save(ssmp);
        return new R(save, save ? "添加成功^_^" : "添加失败-_-!");
    }

    @PutMapping
    public R update(@RequestBody Ssmp ssmp) throws IOException {
        if (ssmp.getName().equals("123")) throw new IOException();
        boolean save = ibookService.update(ssmp);
        return new R(save, save ? "修改成功^_^" : "修改失败-_-!");
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id) {
        return new R(ibookService.removeById(id));
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id) {
        System.out.println("test hot deploy...");
//        System.out.println("test hot deploy...");
        return new R(true, ibookService.getById(id));
    }

    @GetMapping("{currentPage}/{PageSize}")
//    PathVariable代表路径变量
    public R Ipage(@PathVariable int currentPage, @PathVariable int PageSize,Ssmp ssmp) {
        IPage<Ssmp> page = ibookService.getPage(currentPage, PageSize,ssmp);
        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if (currentPage > page.getPages()) {
            page = ibookService.getPage((int) page.getPages(), PageSize,ssmp);
        }
        return new R(true, page);
    }

}